<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>消息</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="css/app.css" />
		<script type="text/javascript" src="script/jquery.js" ></script>
		<script type="text/javascript" src="js/config.js" ></script>
		<style type="text/css">
			.mtime{float: right;font-size: 14px;color:#8f8f94;}
			.mui-table-view .mui-media-object {
			    border-radius: 3px;
			}
			.mui-content>.mui-table-view:first-child {
			    margin-top: 0px;
			}
			.mui-media-body{height: 42px;}
			.bodytop{width: 100%;height: 24px;}
			.bodybot{width: 100%;}
			.bodybot p{width: 85%;float: left;}
			.bodybot span{float: right;}
		</style>
	</head>

	<body>
		<img id="nullmsg" src="images/nullmsg.png" style="width: 130px;position: fixed;z-index: 999;top: 150px;left: 50%;margin-left: -65px;"/>
		<div class="mui-content">
	    	<ul class="mui-table-view" id="msgtips"></ul>
		</div>
		<script src="js/mui.js"></script>
		<script src="js/mui.min.js"></script>
		<script type="text/javascript">
			//mui.init();
			var self;
			mui.plusReady(function(){
				getofflinemsgs();
				self = plus.webview.currentWebview();
				self.setStyle({scrollIndicator:'none'});
				self.setPullToRefresh({support: true,style:'circle'}, pulldownRefresh);
			});
			function pulldownRefresh() {
				var nullmsg =document.getElementById("nullmsg");
				nullmsg.classList.remove("mui-hidden")
				setTimeout(function() {
					window.location.reload(true);
					self.endPullToRefresh();
				}, 1500);
			}
			
			function getofflinemsgs(){
				var tel=window.localStorage.getItem("telephone");
				$.ajax({
					type:"post",
					url:servicePath+"sechandcar/app/message/findByTel",
					data:{targetTel:tel},
					async:false,
					success:function(data){
						if(data==null){
							var msglist = document.getElementById("msgtips");
							msglist.remove();
							return;
						} 
						var map = {},    //临时记录根据某字段分组的临时键值对变量
                        dest = []; 
                         for(var i = 0; i < data.length; i++){    //遍历list数据
                        var ai = data[i];    //ai代表list中的某一项
                        var tbname = "log_log_"+ai.targetID+ai.formID;	
                        db.transaction(function (tx) {  
							tx.executeSql('DROP TABLE '+tbname);
						});
                        if(!map[ai.targetID]){  //临时键值对变量中不存在此键
                            dest.push({     //将此数据以json对象格式放到数组中{key1:value1,key2:value2},key1是分组的字段,key2是list中的某一条数据
                                targetID: ai.targetID,
                                data: [ai]
                            });
                            map[ai.targetID] = ai;    //将未加入map的key放入
                        }else{   //临时键值对中有此键 
                            for(var j = 0; j < dest.length; j++){    //遍历list
                                var dj = dest[j];    //结果数组中某一项数据
                                if(dj.targetID == ai.targetID){    //结果数据中此dest[key1]的值和该list[i].uname的值相等时
                                    dj.data.push(ai);    //把list[i]也放入该dest[key1].data中去
                                    break;
                                }
                                
                            }
                        }
                    }
                         
                         var tmap={},
                         tdest=[];
                           for(var k in dest){
                         	for(var a=0;a<dest[k].data.length;a++){
                         		//alert(dest[k].data.length)
                         		var tai = dest[k].data[a];
                         		var ff = tai.formID+tai.targetID;
                         		//alert(tai.formID+tai.targetID);
                         		if(!tmap[ff]){  //临时键值对变量中不存在此键
		                            tdest.push({     //将此数据以json对象格式放到数组中{key1:value1,key2:value2},key1是分组的字段,key2是list中的某一条数据
		                                formID: ff,
		                                data: [tai]
		                            });
		                            tmap[ff] = tai;    //将未加入map的key放入
		                        }else{   //临时键值对中有此键 
		                            for(var j = 0; j < tdest.length; j++){    //遍历list
		                                var tdj = tdest[j];    //结果数组中某一项数据
		                                if(tdj.formID == tai.formID+tai.targetID){    //结果数据中此dest[key1]的值和该list[i].uname的值相等时
		                                    tdj.data.push(tai);    //把list[i]也放入该dest[key1].data中去
		                                    break;
		                                }
		                                
		                            }
		                        }
		                         	}
		                         }
                         
                         
                         for(var key in tdest){
                         	for(var i=0;i<tdest[key].data.length;i++){
                         		//alert(tdest.[key].data[i].sender);
                         		var smsg= '{"mid":"0","fromtype":"user","fromid":"'+tdest[key].data[i].formID+'","fromname":"'+tdest[key].data[i].fromName+
								'","msgtime":"'+tdest[key].data[i].createDate+'","targetid":"'+tdest[key].data[i].targetID+'","targetname":"'+tdest[key].data[i].targetName+
								'","targettype":"","msgtext":"'+tdest[key].data[i].msgText+'",sender:"'+tdest[key].data[i].sender+'"}';
							saveToLocalDB(eval("("+smsg+")"));
                         	}
                         	//alert(tdest[key].data[0].targetID);
                         	getlastlog(tdest[key].data[0].targetID+tdest[key].data[0].formID);
                         }
					},
				});
			}
			function getlastlog(targetID){
				
				var tablename="log_log_"+targetID;	
				//alert(tablename);
				db.transaction(function (tx) {  
					var sql="SELECT * FROM "+tablename+" order by creatTime desc LIMIT 1";
					tx.executeSql(sql, [], function (tx, results) {
					    var row = results.rows.item(0);
					    var str = '{mid:"'+row.mId+'",fromtype:"'+row.fromType+'",fromid:"'+row.fromId+'",fromname:"'+row.fromName+
									'",msgtime:"'+row.creatTime+'",targetid:"'+row.targetId+'",targetname:"'+row.targetName+
									'",targettype:"'+row.targetType+'",msgtext:"'+row.msgText+'",msgextras:"'+row.msgExtras+'",msgtype:"'+row.msgType+'"}';
					//alert(str);
					addData(eval("("+str+")"));
					}, null);
				});
			}
			function addData(message) {
				if(message.msgtype!="application"){
					var table = document.getElementById("msgtips");
					var tid = message.targetid;
					var fid = message.fromid;
					
					var tname=message.fromname;
					var msgtxt = message.targettype==2?message.fromname+": "+message.msgtext:message.msgtext;
					//mui.toast(message.msgtime);
					var stime = fdt(message.msgtime);
					if(message.targettype==1&&message.fromid==user.id){
						tid = message.targetid;
						tname=message.targetname;
					}
					var values ="'"+tid+"',"+fid+",'"+tname+"'";
					//alert(values);
					var html ='<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red" onclick="delchatlog('+tid+')">删除</a></div>'+ 
								'<div class="mui-slider-handle" onclick="tochat('+values+')" ><a href="javascript:void(0)" style="color:#000000;"><img class="mui-media-object mui-pull-left" src="">'+
								'<div class="mui-media-body"><div class="bodytop">'+tname+'<span class="mtime">'+stime+'</span></div><div class="bodybot">'+
								'<p class="mui-ellipsis">'+msgtxt+'</p><span class="mui-badge mui-badge-danger mui-hidden">1</span></div></div></a></div>';
						var nullmsg =document.getElementById("nullmsg");
						if(html==null||html==""){
							if(nullmsg.classList.contains("mui-hidden")){
								nullmsg.classList.remove("mui-hidden")
							}
						}else{
							if(!nullmsg.classList.contains("mui-hidden")){
								nullmsg.classList.add("mui-hidden")
							}
						}
					var mli = document.getElementById("traget-"+tid+fid);
					if(mli!=null){
						mli.innerHTML = html;
					}else{
						var li = document.createElement('li');
						li.id="traget-"+tid;
						li.className = 'mui-table-view-cell mui-media';
						li.innerHTML = html;
						table.insertBefore(li, table.firstChild);
					}
				}
			}
			function delchatlog(id){
				var tname = "log_log_"+id;
				db.transaction(function (tx) {  
					tx.executeSql('DROP TABLE '+tname);
				});
				var msglist = document.getElementById("msgtips");
				var child = document.getElementById("traget-"+id);
				if(child!=null){
					msglist.removeChild(child);
				}
			}
			function tochat(id,fid,name){
				window.localStorage.setItem("chatid",id);
				window.localStorage.setItem("fromid",fid);
				window.localStorage.setItem("chatname",name);
				//plus.webview.getWebviewById("chatpage.html").evalJS("initpage()");
				mui.openWindow({url:'chatpage.html',id:'chatpage.html'});
				//plus.webview.getWebviewById("index.html").evalJS("removebadge('message')");
			}
			
		</script>
	</body>

</html>